package models

import (
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	_ "github.com/go-sql-driver/mysql"
	"github.com/gogf/gf/util/gconv"
	"mdblog/models/analysis"
	"mdblog/models/auth"
	"mdblog/models/blog"
	"time"
)

func init() {
	// 注册驱动
	_ = orm.RegisterDriver("mysql", orm.DRMySQL)
	// 注册默认数据库
	dbUrl := beego.AppConfig.DefaultString("mysqlUrl", "root:root@tcp(127.0.0.1:3306)/site?charset=utf8mb4&loc=Asia%2FShanghai")
	_ = orm.RegisterDataBase("default", "mysql", dbUrl)

	// 注册数据表
	orm.RegisterModel(new(auth.User))

	// 分析相关
	orm.RegisterModel(new(analysis.SiteVisit))

	// blog 相关数据表
	orm.RegisterModel(new(blog.Article))
	orm.RegisterModel(new(blog.Classify))
	orm.RegisterModel(new(blog.Target))
	orm.RegisterModel(new(blog.Resources))
	orm.RegisterModel(new(blog.Notice))
	orm.RegisterModel(new(blog.Carousel))

	// 同步数据库
	_ = orm.RunSyncdb("default", false, true)

	// 初始化全局配置
	value, err := GetOneConfig("init")
	if err != nil {
		if err != orm.ErrNoRows {
			panic(err)
		}
	}
	if !gconv.Bool(value) {
		_ = CreateConfig("init", "true", "初始化配置开关")
		_ = CreateConfig("SiteTitle", "默认站点", "站点名称")
		_ = CreateConfig("SiteUrl", "http://127.0.0.1", "站点地址")
		_ = CreateConfig("KeyWords", "默认的关键字", "Seo keywords")                          // Seo keywords
		_ = CreateConfig("Description", "默认描述", "Seo 描述")                               // Seo 描述
		_ = CreateConfig("EnableMovie", "false", "开启电影功能")                              // 开启电影功能
		_ = CreateConfig("EnableNovel", "false", "开启小说功能")                              // 开启小说功能
		_ = CreateConfig("EnableComment", "false", "开启评论功能")                            // 开启评论功能
		_ = CreateConfig("PageSize", "10", "每页文章数量")                                    // 每页文章数量
		_ = CreateConfig("LogoImages", "/static/blog/static/images/logo.png", "网站Logo") // 网站Logo
		_ = CreateConfig("BenAn", "默认备案号", "备案号")
		_ = CreateConfig("Author", "默认作者", "文章默认作者")
		_ = CreateConfig("UploadPath", "upload", "资源上传路径")
		_ = CreateConfig("BannerUrl", "/static/blog/static/images/banner.jpg", "文章页面banner图片地址,图片尺寸推荐")
		_ = auth.CreateAdminUserAccount("admin", "admin", "admin@local.com")
		_ = blog.CreateNotice("系统创建公告", "系统创建默认公告", time.Now(), time.Now())
		_ = blog.SetDefaultNotice(1)

		startAt := time.Now()
		endAt := time.Date(2099, 12, 31, 23, 59, 59, 1, time.Local)
		_ = blog.CreateCarousel("/static/blog/static/images/ad1.jpg", "", startAt, endAt, "系统默认创建")
		_ = blog.CreateCarousel("/static/blog/static/images/ad2.jpg", "", startAt, endAt, "系统默认创建")
		_ = blog.CreateCarousel("/static/blog/static/images/ad3.jpg", "", startAt, endAt, "系统默认创建")
	}
}
